package com.bootdo.common.oss;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.bootdo.common.domain.OssStorageDO;
import com.bootdo.common.enums.QiniuZone;
import com.bootdo.common.oss.bean.Aliyun;
import com.bootdo.common.oss.bean.Qiniu;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Service;

import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;

/**
 * @author guoyunfei on 2021/7/7 22:51
 * @className AttachFileService
 * @description TODO
 * @Version 1.0
 */

@Service
public class AttachFileService {

    @Resource
    private Qiniu qiniu;

    @Resource
    private Aliyun aliyun;

    public final static String NORM_MONTH_PATTERN = "yyyy/MM/dd/";


    public com.qiniu.storage.Configuration qiniuZone(String zoneStr) {
        Zone zone = null;
        if (Objects.equals(zoneStr, QiniuZone.HUA_BEI)) {
            zone = Zone.huabei();
        } else if (Objects.equals(zoneStr, QiniuZone.HUA_DONG)) {
            zone = Zone.huadong();
        } else if (Objects.equals(zoneStr, QiniuZone.HUA_NAN)) {
            zone = Zone.huanan();
        } else if (Objects.equals(zoneStr, QiniuZone.BEI_MEI)) {
            zone = Zone.beimei();
        } else if (Objects.equals(zoneStr, QiniuZone.XIN_JIA_PO)) {
            zone = Zone.xinjiapo();
        }
        return new com.qiniu.storage.Configuration(zone);
    }

    public Zone getQiniuZone(String zoneStr) {
        Configuration configuration = qiniuZone(zoneStr);
        return configuration.zone;
    }

    /**
     * 上传文件(七牛云)
     * @param file
     * @return
     * @throws QiniuException
     */
    public String uploadFileQiniu(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        String extName = FileUtil.extName(filename);
        //String rFileName = DateUtil.format(new Date(), NORM_MONTH_PATTERN) + IdUtil.simpleUUID() + "." + extName;
        String rFileName =  IdUtil.simpleUUID() + "." + extName;
        //存储东南亚
        Configuration cfg = new Configuration(Zone.zone0());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(qiniu.getAccessKey(), qiniu.getSecretKey());
        String upToken = auth.uploadToken(qiniu.getBucket(), rFileName);
        Response response = uploadManager.put(file.getBytes(), rFileName, upToken);

        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        System.out.println(putRet);
        return rFileName;
    }

    /**
     * 上传文件(阿里云)
     * @param file
     * @return
     * @throws QiniuException
     */
    public String uploadFileAliyun(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        String extName = FileUtil.extName(filename);
        //String rFileName = DateUtil.format(new Date(), NORM_MONTH_PATTERN) + IdUtil.simpleUUID() + "." + extName;
        String rFileName = IdUtil.simpleUUID() + "." + extName;

        OSS oss = new OSSClientBuilder().build(aliyun.getEndpoint(), aliyun.getAccessKeyId(), aliyun.getAccessKeySecret());
        //流式上传-文件流
        PutObjectRequest putObjectRequest = new PutObjectRequest(aliyun.getBucket(), rFileName, new ByteArrayInputStream(file.getBytes()));
        oss.putObject(putObjectRequest);
        oss.shutdown();
        return rFileName;
    }

    public boolean deleteAliyun (String fileName){
        OSS ossClient = new OSSClientBuilder().build(aliyun.getEndpoint(), aliyun.getAccessKeyId(), aliyun.getAccessKeySecret());
        // 删除文件或目录。如果要删除目录，目录必须为空。
        ossClient.deleteObject(aliyun.getBucket(), fileName);
        // 关闭OSSClient。
        ossClient.shutdown();
        return true;
    }

    public int deleteQiniu (String fileName){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zoneAs0());
        Auth auth = Auth.create(qiniu.getAccessKey(), qiniu.getSecretKey());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            Response delete = bucketManager.delete(qiniu.getBucket(), fileName);
            return delete.statusCode;
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            ex.printStackTrace();
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
        return -1;
    }


    // TODO ================================上传版本2=============================================

    /**
     * 上传文件(七牛云)
     * @param file
     * @return
     * @throws QiniuException
     */
    public String uploadFileQiniu(MultipartFile file,OssStorageDO ossStorage) throws IOException {
        String filename = file.getOriginalFilename();
        String extName = FileUtil.extName(filename);
        //String rFileName = DateUtil.format(new Date(), NORM_MONTH_PATTERN) + IdUtil.simpleUUID() + "." + extName;
        String rFileName =  IdUtil.simpleUUID() + "." + extName;
        //存储区域
        Configuration cfg = new Configuration(getQiniuZone(ossStorage.getOssZone()));
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(ossStorage.getOssAccesskey(), ossStorage.getOssSecretkey());
        String upToken = auth.uploadToken(ossStorage.getOssBucket(), rFileName);

        //byte[] bytes = ImgUtils.compressPicByQuality(file.getBytes(), 0.7F);
        Response response = uploadManager.put(file.getBytes(), rFileName, upToken);
        //DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        return rFileName;
    }

    /**
     * 上传文件(阿里云)
     * @param file
     * @return
     * @throws QiniuException
     */
    public String uploadFileAliyun(MultipartFile file,OssStorageDO ossStorage) throws IOException {
        String filename = file.getOriginalFilename();
        String extName = FileUtil.extName(filename);
        //String rFileName = DateUtil.format(new Date(), NORM_MONTH_PATTERN) + IdUtil.simpleUUID() + "." + extName;
        String rFileName =  IdUtil.simpleUUID() + "." + extName;

        OSS oss = new OSSClientBuilder().build(ossStorage.getOssEndpoint(), ossStorage.getOssAccesskey(), ossStorage.getOssSecretkey());
        //流式上传-文件流
        PutObjectRequest putObjectRequest = new PutObjectRequest(ossStorage.getOssBucket(), rFileName,
                new ByteArrayInputStream(file.getBytes()));
        oss.putObject(putObjectRequest);
        oss.shutdown();
        return rFileName;
    }

    public boolean deleteAliyun (String fileName,OssStorageDO ossStorage){
        OSS ossClient = new OSSClientBuilder().build(ossStorage.getOssEndpoint(), ossStorage.getOssAccesskey(), ossStorage.getOssSecretkey());
        // 删除文件或目录。如果要删除目录，目录必须为空。
        ossClient.deleteObject(ossStorage.getOssBucket(), fileName);
        // 关闭OSSClient。
        ossClient.shutdown();
        return true;
    }

    public int deleteQiniu (String fileName,OssStorageDO ossStorage){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zoneAs0());
        Auth auth = Auth.create(ossStorage.getOssAccesskey(), ossStorage.getOssSecretkey());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            Response delete = bucketManager.delete(ossStorage.getOssBucket(), fileName);
            return delete.statusCode;
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            ex.printStackTrace();
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
        return -1;
    }




}
